package com.sunday.pinxinghui.model.index;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.RecyclerTabLayout;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.IndexAdHolder;
import com.sunday.pinxinghui.adapter.IndexMiaoShaAdapter;
import com.sunday.pinxinghui.adapter.IndexTodaysAdapter;
import com.sunday.pinxinghui.adapter.LimitTimePageAdapter;
import com.sunday.pinxinghui.adapter.LimitTimeTabAdapter;
import com.sunday.pinxinghui.base.BaseLazyFragment;
import com.sunday.pinxinghui.entity.BannerImg;
import com.sunday.pinxinghui.entity.HeadData;
import com.sunday.pinxinghui.entity.IndexProduct;
import com.sunday.pinxinghui.entity.LimitTime;
import com.sunday.pinxinghui.model.main.IndexFragment;
import com.sunday.pinxinghui.model.products.MiaoShaProductListActivity;
import com.sunday.pinxinghui.model.products.ProductDetailActivity;

import com.sunday.pinxinghui.model.products.ProductsListActivity;
import com.sunday.pinxinghui.network.ApiClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/8/7.
 * 今日特卖
 */

public class TodayFragment extends BaseLazyFragment {


    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.check_more_miaosha)
    LinearLayout checkMoreMiaosha;
    @Bind(R.id.miaosha_recycler_view)
    RecyclerView miaoshaRecyclerView;
    @Bind(R.id.id_stickynavlayout_topview)
    LinearLayout header;
    @Bind(R.id.recycler_tablayout)
    RecyclerTabLayout recyclerTabLayout;
    @Bind(R.id.recycler_tablayout_view_pager)
    ViewPager viewPager;
    @Bind(R.id.id_stickynavlayout_indicator)
    LinearLayout linearLayout;
    @Bind(R.id.id_stickynavlayout_viewpager)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;


    private List<LimitTime> timeList = new ArrayList<>();
    private int pageNo = 1;
    private boolean isCanloadMore;
    private List<IndexProduct> productList = new ArrayList<>();
    private List<IndexProduct> miaoshaList = new ArrayList<>();
    private int lastVisibleItem;
    private LinearLayoutManager layoutManager, mLayoutManager;
    private IndexTodaysAdapter adapter;
    private LimitTimePageAdapter pageAdapter;
    private IndexMiaoShaAdapter mAdapter;

    public static TodayFragment newInstance() {
        TodayFragment fragment = new TodayFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.today_fragment, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initRecylcerTab();
        getHeadData();
    }

    @OnClick(R.id.check_more_miaosha)
    void onClick() {
        intent = new Intent(mContext, MiaoShaProductListActivity.class);
        startActivity(intent);
    }


    private void initView() {
        adapter = new IndexTodaysAdapter(mContext, productList);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider_width).build());
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getProducts();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        adapter.notifyDataSetChanged();
        //秒杀
        mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        miaoshaRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new IndexMiaoShaAdapter(mContext, miaoshaList);
        miaoshaRecyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getHeadData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                //return PtrDefaultHandler.checkContentCanBePulledDown(frame,content , header);
                if (!((IndexFragment) getParentFragment()).checkTabLayoutVisible() && !checkBannerVisible()) {
                    return true;
                }
                return false;
            }
        });
        ptrFrame.disableWhenHorizontalMove(true);



    }

    public boolean checkBannerVisible() {
        boolean cover = false;
        Rect rect = new Rect();
        cover = banner.getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= banner.getMeasuredWidth() && rect.height() >= banner.getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }

    private void initRecylcerTab() {
        pageAdapter = new LimitTimePageAdapter(mContext, timeList);
        viewPager.setAdapter(pageAdapter);
        recyclerTabLayout.setUpWithAdapter(new LimitTimeTabAdapter(viewPager));
        recyclerTabLayout.setAutoSelectionMode(true);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) recyclerTabLayout.getLayoutParams();
        recyclerTabLayout.setLayoutParams(params);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                timeLimitId = timeList.get(position).getTimeId();
                adapter.setType(timeList.get(position).getType());
                pageNo=1;
                getProducts();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //轮播图和秒杀产品
    private void getHeadData() {
        Call<ResultDO<HeadData>> call = ApiClient.getApiAdapter().getIndexHeadData();
        call.enqueue(new Callback<ResultDO<HeadData>>() {
            @Override
            public void onResponse(Call<ResultDO<HeadData>> call, Response<ResultDO<HeadData>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    updateHead(response.body().getResult());
                    getLimitTimeList();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<HeadData>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void updateHead(HeadData headData) {
        if (headData == null) {
            return;
        }
        List<BannerImg> bannerImgs = new ArrayList<>();
        if (headData.getBanners() != null && headData.getBanners().size() > 0) {
            bannerImgs.clear();
            bannerImgs.addAll(headData.getBanners());
        }
        banner.startTurning(3000);
        final IndexAdHolder indexAdHolder = new IndexAdHolder();
        banner.setPages(new ViewHolderCreator<IndexAdHolder>() {
            @Override
            public IndexAdHolder createHolder() {
                return indexAdHolder;
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();
        indexAdHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BannerImg item = (BannerImg) v.getTag();
                if (item.getLinkType() != null && item.getLinkType() == 1) {
                    intent = new Intent(mContext, ProductDetailActivity.class);
                    intent.putExtra("productId", item.getProductId());
                    startActivity(intent);
                }else if (item.getCatId()!=0){
                    //intent = new Intent(mContext, ProductListActivity.class);
                    intent = new Intent(mContext, ProductsListActivity.class);
                    intent.putExtra("parentId",item.getParentCatId());
                    intent.putExtra("catId", item.getCatId());
                    intent.putExtra("parentName", item.getName());
                    startActivity(intent);
                }
            }
        });
        miaoshaList.clear();
        miaoshaList.addAll(headData.getLimitCountProducts());
        mAdapter.notifyDataSetChanged();


    }

    private int timeLimitId;

    private void getLimitTimeList() {
        Call<ResultDO<List<LimitTime>>> call = ApiClient.getApiAdapter().getLimitBuyTime();
        call.enqueue(new Callback<ResultDO<List<LimitTime>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<LimitTime>>> call, Response<ResultDO<List<LimitTime>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<List<LimitTime>> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    timeList.clear();
                    timeList.addAll(resultDO.getResult());
                    pageAdapter.notifyDataSetChanged();
                    if (timeList != null && timeList.size() > 0) {
                        for (int i = 0; i < timeList.size(); i++) {
                            if (timeList.get(i).getType() == 2) {
                                timeLimitId = timeList.get(i).getTimeId();
                                viewPager.setCurrentItem(i, false);
                                break;
                            }
                        }
                    }
                    pageNo = 1;
                    getProducts();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<LimitTime>>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


    private void getProducts() {
        Call<ResultDO<List<IndexProduct>>> call = ApiClient.getApiAdapter().getLimitBuyProduct(timeLimitId, 1, pageNo, Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<IndexProduct>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<IndexProduct>>> call, Response<ResultDO<List<IndexProduct>>> response) {
                ResultDO<List<IndexProduct>> resultDO = response.body();
                if (isFinish || resultDO == null) {
                    return;
                }
                ptrFrame.refreshComplete();
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() != null) {
                        if (pageNo == 1) {
                            productList.clear();
                        }
                        productList.addAll(resultDO.getResult());
                        if (resultDO.getResult().size() == Constants.PAGE_SIZE) {
                            isCanloadMore = true;
                            pageNo++;
                        } else {
                            isCanloadMore = false;
                        }
                    }
                    adapter.setTimeLimitId(timeLimitId);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<IndexProduct>>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
                ptrFrame.refreshComplete();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getHeadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
